package ltd.simulatoruidemo.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import ltd.simulatoruidemo.fragment.LayoutFragment;
import ltd.viewpager.JazzyViewPager;

/**
 * Created by chinalin on 2017/5/9.
 */

public class MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
    private String[] tabTilte;

    private List<LayoutFragment> listFragment;
    private FragmentManager fm;
    private JazzyViewPager mViewPager;

    public MyFragmentStatePagerAdapter(FragmentManager fm, List<LayoutFragment> listFragment,JazzyViewPager mViewPager) {
        super(fm);
        this.fm = fm;
        this.listFragment = listFragment;
        this.mViewPager = mViewPager;
    }

    /**
     * 更改listFragment的内容，刷新
     * @param fragments
     */
    public void setFragments(List<LayoutFragment> fragments) {
        if(this.listFragment != null){
            FragmentTransaction ft = fm.beginTransaction();
            for(Fragment f:this.listFragment){
                ft.remove(f);
            }
            ft.commit();
            ft=null;
            fm.executePendingTransactions();        //立刻执行ft.commit
        }
        this.listFragment = fragments;
        notifyDataSetChanged();                     //刷新view
    }

    @Override
    public Fragment getItem(int position) {
        return listFragment.get(position);
    }


    @Override
    public int getCount() {
        return listFragment.size();
    }

    //**************加上下面的两行即可实现换页时的动画效果*********************************//

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Object obj = super.instantiateItem(container, position);
        this.mViewPager.setObjectForPosition(obj, position);
        return obj;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        if (object != null) {
            return ((Fragment) object).getView() == view;
        } else {
            return false;
        }
    }
}
